<?php
/**
 * Handler File Class
 *
 * @author liliang <liliang@wolive.cc>
 * @email liliang@wolive.cc
 * @date 2017/06/01
 */

namespace app\index\controller;

use think\Controller;
use app\extra\push\Pusher;
use app\index\model\User;
use app\Common;

/**
 *
 * 前台Pc端对话窗口.
 */
class Index extends Controller
{
 
   /**
    * 
    * [home description]
    * @return [type] [description]
    */
   public function home(){
       $res = User::table('wolive_service')->where('is_del', 0)->update(['state' => 'online']);

       $data=$this->request->request();


    if(!isset($data['product'])){
        $data['product'] ="";
    }

    $str ="visiter_id=".$data['visiter_id']."&visiter_name=".$data['visiter_name']."&avatar=".$data['avatar']."&business_id=".$data['business_id']."&groupid=".$data['groupid']."&product=".$data['product'];

    $common=new Common();

    $newstr =$common->encrypt($str, 'E', 'wolive');
  
    $a =urlencode($newstr);

    $_SESSION['saa_key'] = $data['business_id'];
    $this->redirect('/index/index?code='.$a);

   }

    /**
     * 对话窗口页面.
     *
     * @return mixed
     */
    public function index()
    {
        $res = User::table('wolive_service')->where('is_del', 0)->update(['state' => 'online']);
        $sarr = parse_url(ahost);
        if($sarr['scheme'] == 'https'){
            $state = true;
        }else{
            $state =false;
        }

        $app_key = app_key;
        $app_secret = app_secret;
        $app_id = app_id;
        $options = array(
            'encrypted' => $state
        );
        $host = ahost;
        $port = aport;

        $pusher = new Pusher(
            $app_key,
            $app_secret,
            $app_id,
            $options,
            $host,
            $port
        );

        $common=new Common();

        $is_mobile =$common->isMobile();

        $url = domain;

        if(isset($_SERVER['HTTP_REFERER'])){
           $from_url=$_SERVER['HTTP_REFERER'];
         }else{
           $from_url='';
         }

      
        $arr =$this->request->get();

        $data =$common->encrypt($arr['code'],'D','wolive');

        if(!$data){
          $this->redirect('index/index/errors');
        }
           
        parse_str($data,$arr2);

        if(!isset($arr2['visiter_id']) || !isset($arr2['visiter_name']) || !isset($arr2['product']) || !isset($arr2['groupid']) || !isset($arr2['business_id']) || !isset($arr2['avatar'])){
           $this->redirect('index/index/errors');
        }
       

        if($is_mobile){
            $this->redirect('/mobile/index/home?visiter_id='.$arr2['visiter_id'].'&visiter_name='.$arr2['visiter_name'].'&avatar='.$arr2['avatar'].'&business_id='.$arr2['business_id'].'&product='.$arr2['product'].'&groupid='.$arr2['groupid']);
        }


        $content =json_decode($arr2['product'], true); 
        if(!$content){
          $arr2['product'] =NULL;

        }
        $business_id =htmlspecialchars($arr2['business_id']);
       
      // 判断是否访问过
      if(!isset($_COOKIE['visiter_id'])){

           if($arr2['visiter_id']){
              $visiter_id=htmlspecialchars($arr2['visiter_id']);
           }else{
              $visiter_id=$common->rand(2);
           }
           setcookie("visiter_id",$visiter_id,time()+3600*12);
           
           if(!isset($_COOKIE['product_id'])){
         
              if($arr2['product'] != NULL){
                
                  $product=$arr2['product'];
                  $content =json_decode($arr2['product'], true); 
                  setcookie("product_id",$content['pid'],time()+3600*12);
                  $arr2['timestamp'] =time();

                  $service =User::table('wolive_queue')->where(['visiter_id'=>$visiter_id,'business_id'=>$business_id])->find();

                   if($service){
                     $service_id =$service['service_id'];
                   }else{
                     $service_id =0;
                   }

                    $str ='<a href="'.$content['url'].'" target="_blank" class="wolive_product">';
                    $str .='<div class="wolive_img"><img src="'.$content['img'].'" width="100px"></div>';
                    $str .='<div class="wolive_head"><p>'.$content['title'].'<span class="wolive_price">'.$content['price'].'</span><p>';
                    $str .='<p class="wolive_info">'.$content['info'].'</p>';
                    $str .='</div></a>';
                  

                  $mydata =['service_id'=>$service_id,'visiter_id'=>$visiter_id,'content'=>$str,'timestamp'=>time(),'business_id'=>$business_id,'direction'=>'to_service'];

                  $pusher->trigger('kefu'.$service_id, 'cu-event', array('message' => $mydata));

                  $chats =User::table('wolive_chats')->insert($mydata);

              }
           }else{

             $pid =$_COOKIE['product_id'];
           
             if($arr2['product'] != NULL){
                $product=$arr2['product'];
                $content =json_decode($arr2['product'], true); 

                if($content['pid'] != $pid){

                    $service =User::table('wolive_queue')->where(['visiter_id'=>$visiter_id,'business_id'=>$business_id])->find();

                     if($service){
                       $service_id =$service['service_id'];
                     }else{
                       $service_id =0;
                     }

                    $str ='<a href="'.$content['url'].'" target="_blank" class="wolive_product">';
                    $str .='<div class="wolive_img"><img src="'.$content['img'].'" width="100px"></div>';
                    $str .='<div class="wolive_head"><p>'.$content['title'].'<span class="wolive_price">'.$content['price'].'</span><p>';
                    $str .='<p class="wolive_info">'.$content['info'].'</p>';
                    $str .='</div></a>';

                    $mydata =['service_id'=>$service_id,'visiter_id'=>$visiter_id,'content'=>$str,'timestamp'=>time(),'business_id'=>$business_id,'direction'=>'to_service'];

                    $pusher->trigger('kefu'.$service_id, 'cu-event', array('message' => $mydata));
                    $chats =User::table('wolive_chats')->insert($mydata);
                    
                }
             }
           }

        }else{

           if($arr2['visiter_id']){

              $visiter_id=$arr2['visiter_id'];
           }else{
              $visiter_id =$_COOKIE['visiter_id'];
           }
           
          

           if(!isset($_COOKIE['product_id'])){

              if($arr2['product'] != NULL){
                  $product=$arr2['product'];
                  $content =json_decode($arr2['product'], true); 
                  setcookie("product_id",$content['pid'],time()+3600*12);
                  $arr2['timestamp'] =time();

                  $service =User::table('wolive_queue')->where(['visiter_id'=>$visiter_id,'business_id'=>$business_id])->find();

                   if($service){
                     $service_id =$service['service_id'];
                   }else{
                     $service_id =0;
                   }

                    $str ='<a href="'.$content['url'].'" target="_blank" class="wolive_product">';
                    $str .='<div class="wolive_img"><img src="'.$content['img'].'" width="100px"></div>';
                    $str .='<div class="wolive_head"><p>'.$content['title'].'<span class="wolive_price">'.$content['price'].'</span><p>';
                    $str .='<p class="wolive_info">'.$content['info'].'</p>';
                    $str .='</div></a>';
                  

                  $mydata =['service_id'=>$service_id,'visiter_id'=>$visiter_id,'content'=>$str,'timestamp'=>time(),'business_id'=>$business_id,'direction'=>'to_service'];

                  $pusher->trigger('kefu'.$service_id, 'cu-event', array('message' => $mydata));

                  $chats =User::table('wolive_chats')->insert($mydata);
                 
              }
           }else{

             if($arr2['product'] != NULL){


             if($arr2['visiter_id'] !=$_COOKIE['visiter_id'] ){

                   $product=$arr2['product'];
                   $content =json_decode($arr2['product'], true); 
               
                   $service =User::table('wolive_queue')->where(['visiter_id'=>$visiter_id,'business_id'=>$business_id])->find();

                     if($service){
                       $service_id =$service['service_id'];
                     }else{
                       $service_id =0;
                     }

                    $str ='<a href="'.$content['url'].'" target="_blank" class="wolive_product">';
                    $str .='<div class="wolive_img"><img src="'.$content['img'].'" width="100px"></div>';
                    $str .='<div class="wolive_head"><p>'.$content['title'].'<span class="wolive_price">'.$content['price'].'</span><p>';
                    $str .='<p class="wolive_info">'.$content['info'].'</p>';
                    $str .='</div></a>';
                  

                    $mydata =['service_id'=>$service_id,'visiter_id'=>$visiter_id,'content'=>$str,'timestamp'=>time(),'business_id'=>$business_id,'direction'=>'to_service'];

                    $pusher->trigger('kefu'.$service_id, 'cu-event', array('message' => $mydata));
                    $chats =User::table('wolive_chats')->insert($mydata);

             }else{
                
                $pid =$_COOKIE['product_id'];
      
                    $product=$arr2['product'];
                    $content =json_decode($arr2['product'], true); 
                    // 判断是否是同个商品
                    if($content['pid'] != $pid){

                        $service =User::table('wolive_queue')->where(['visiter_id'=>$visiter_id,'business_id'=>$business_id])->find();

                         if($service){
                           $service_id =$service['service_id'];
                         }else{
                           $service_id =0;
                         }

                        $str ='<a href="'.$content['url'].'" target="_blank" class="wolive_product">';
                        $str .='<div class="wolive_img"><img src="'.$content['img'].'" width="100px"></div>';
                        $str .='<div class="wolive_head"><p>'.$content['title'].'<span class="wolive_price">'.$content['price'].'</span><p>';
                        $str .='<p class="wolive_info">'.$content['info'].'</p>';
                        $str .='</div></a>';
                      

                        $mydata =['service_id'=>$service_id,'visiter_id'=>$visiter_id,'content'=>$str,'timestamp'=>time(),'business_id'=>$business_id,'direction'=>'to_service'];

                        $pusher->trigger('kefu'.$service_id, 'cu-event', array('message' => $mydata));
                        $chats =User::table('wolive_chats')->insert($mydata);
                  }
               }

             }
           }
        }
          
        $channel =bin2hex($visiter_id.'/'.$business_id);
        $visiter_name =htmlspecialchars($arr2['visiter_name']);

        $avatar =htmlspecialchars($arr2['avatar']);
        
        if($visiter_name == ''){
            $visiter_name='游客'.$visiter_id;
        }

        $groupid =htmlspecialchars($arr2['groupid']);

        $app_key = app_key;
        $whost = whost;
        $arr = parse_url($whost);
        if($arr['scheme'] == 'ws'){

            $port ='wsPort';
            $value ='false';
        }else{

            $value ='true';
            $port ='wssPort';
        }
    
        $business =User::table('wolive_business')->where('business_id',$business_id)->find();
           
        $this->assign("type",$business['video_state']);
        $this->assign("atype",$business['audio_state']);
        $this->assign('app_key', $app_key);
        $this->assign('whost', $arr['host']);
        $this->assign('value', $value);
        $this->assign('wport', wport);;
        $this->assign('port',$port);
        $this->assign('url',$url);
        $this->assign('groupid',$groupid);
        $this->assign('visiter',$visiter_name);
        $this->assign('business_id',$business_id);
        $this->assign('from_url',$from_url);
        $this->assign('channel',$channel);
        $this->assign('visiter_id',$visiter_id);
        $this->assign('avatar',$avatar);

        return $this->fetch();
    }

    /**
     * 404页面
     */
    
    public function errors(){
      return $this->fetch();
    }

    /**
     * 获取排队数量.
     *
     * @return mixed
     */
    public  function getwaitnum()
    {
        $post = $this->request->post();
        $num  =User::table('wolive_queue')->where('visiter_id',$post['visiter_id'])->where("service_id",0)->count();
        return $result;
    }

  
}
